package com.chixing.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.commons.WebSocketProcess2;
import com.chixing.mapper.CouponMapper;
import com.chixing.pojo.Coupon;
import com.chixing.pojo.CustomerTokenDTO;
import com.chixing.pojo.Mycoupon;
import com.chixing.service.IMycouponService;
import com.chixing.utils.TokenUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class MyCouponController {
    @Autowired
    private IMycouponService iMycouponService;
    //    注入webSocket
    @Autowired
    private WebSocketProcess2 webSocketProcess2;
    @Autowired
    private CouponMapper couponMapper;

    @GetMapping("mycoupon")
    @ResponseBody
    public List<Mycoupon> getAll(HttpServletRequest request){
        String token = request.getHeader("token");
        CustomerTokenDTO customerTokenDTO = TokenUtil.parseToken(token);
        Integer userId = customerTokenDTO.getCustId();
        List<Mycoupon> mycouponList = iMycouponService.selectAll(userId);
        return mycouponList;
    }
    //    根据用户的优惠券过期时间在一定时间内进行消息推送
//    给指定的id发送消息
    @RabbitHandler
    @RabbitListener(queues = "webSocketCouponQueue")
    public void sendMsgToClientById(Channel channel, Message message, Map map) {
        Integer id = (Integer) map.get("id");
        String userName =(String) map.get("userName");
        List<Mycoupon> mycouponList = iMycouponService.selectAll(id);
        for (Mycoupon mycoupon : mycouponList) {
//            String endTime = mycoupon.getXx();
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            查询优惠卷的结束时间
            QueryWrapper<Coupon> wrapper = new QueryWrapper<>();
            wrapper.eq("coupon_id", mycoupon.getCouponId());
            Coupon coupon = couponMapper.selectOne(wrapper);
//            转换日期格式
            LocalDateTime couponEndTime = coupon.getCouponEndTime();
            Date date = Date.from( couponEndTime.atZone( ZoneId.systemDefault()).toInstant());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(date);
//            相差小时数来判断是否给用户发送消息或者以相差分钟数
            int hour = couponEndTime.getHour();
            System.out.println("1:" + hour);
            int hour1 = LocalDateTime.now().getHour();
            System.out.println("2:" + hour1);
//            判断用户当前已拥有的优惠券是否快过期
//            若快过期就发送消息提醒用户去使用
            if (hour > hour1 && hour - hour1 ==2) {
                String msg=userName+"你好：你的："+coupon.getCouponRule()+"的优惠券在"+format+"到期，请你及时使用";
                try {
                    webSocketProcess2.sendMessage(userName, msg);
                    System.out.println("-------------------->>>");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //    用户删除优惠券
    @PostMapping("deleteCoupon/{number}")
    @ResponseBody
    public String deleteCoupon(@PathVariable("number") String mycouponNumber){

        Integer delete = iMycouponService.delete(mycouponNumber);
        if(delete>0){
            return "删除成功";
        }
        return "删除失败";
    }
}
